<template>
   <view class="my-image-container"   :class="class" :style="{ width: width, height: height,  borderRadius: radius ? `${radius}px` : '0'}"   >
       <template  v-if="src" >
            <!-- 图片加载中提示 -->
            <view  class="loading-tip"  v-if="isLoading && !isError">
              <text :style="{fontSize: fontSize}">加载中</text>
            </view>
            <!-- 图片加载失败提示 -->
            <view  class="error-tip" v-if="isError">
              <text :style="{fontSize: fontSize}">加载失败</text>
            </view>
            <!-- 图片本身 -->
            <image  :src="src"  :mode="mode" class="my-image" :lazy-load="lazyLoad"  @load="handleImageLoad"  @error="handleImageError"
                :style="{  display: (isLoading || isError) ? 'none' : 'block', borderRadius: radius ? `${radius}px` : '0'}"></image>
       </template>
       <template v-else>
            <view  class="error-tip">
                <text>加载失败</text>
            </view>
       </template>
   </view> 
</template>

<script setup lang="ts">
import { ref } from 'vue';

// 定义组件属性
const props = defineProps({
  src: {
    type: String || null,
    default: ''
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  radius: {
    type: [Number, String],
    default: 0
  },
  lazyLoad: {
    type: Boolean,
    default: false
  },
  fontSize: {
    type: String,
    default: '10px'
  },
  mode: {
    type: String,
    default: 'scaleToFill'
  },
  class: {
    type: String,
    default: ''
  }
});

// 状态管理
const isLoading = ref(true);
const isError = ref(false);

// 图片加载完成处理
const handleImageLoad = () => {
  isLoading.value = false;
  isError.value = false;
};

// 图片加载失败处理
const handleImageError = () => {
  isLoading.value = false;
  isError.value = true;
};
</script>

<style scoped>
.my-image-container {
  overflow: hidden;
  display: inline-block;
  position: relative;
  background-color: #ffffff;
}

.my-image {
  width: 100%;
  height: 100%;
  display: block;
  background-color: #fff;
  object-fit: cover;
}

.loading-tip, .error-tip {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}

.loading-tip text, .error-tip text {
  font-size: 10px;
  color: #999;
}
</style>
